package com.bw.base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

open class BaseViewModel:ViewModel() {


    fun<T> httpReguest(s:suspend ()-> Res<T>,success:(T)->Unit){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val res = s.invoke()
                if (res.code==200){
                    success(res.data)
                }else{
                    Log.i("park", "httpReguest: ${res.messgae}")
                }
            }catch (e:Exception){
                Log.i("park", "httpReguest: ${e.message.toString()}")
                e.printStackTrace()
            }
        }
    }
    fun mapToBody(map:Any):RequestBody{
        val toJson = Gson().toJson(map)
        return RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),toJson)
    }
}